/**
 * 用户举报/反馈/建议 路由
 */

var router = require('express').Router();
var userTool = require('../bin/user');
var dbentityTool = require('../bin/dbentity');
var ObjectID = require('mongodb').ObjectID;
var articleTool = require('../bin/article');
var feedbackConvention = require('../convention/feedback_convention');
var conventionTool = require('../bin/convention');
var assertAlljs = require('../bin/util/assert-alljs');
var datetimeTool = require('../bin/util/datetime');

router.post('/feedbackcommit', async function(req, res){
    let assert = assertAlljs(req, res);
    if (await assert(req.body.captcha.toLowerCase() !== req.session.captcha.toLowerCase(), '验证码错误!'))
        return;

    let user = req.session.user;

    let feedback = conventionTool.convert(req.body, feedbackConvention);

    feedback.ip = req.session.ip;
    if (user)
        feedback.produceUser = userTool.getProfile(user);
    feedback.produceTime = new Date().getTime();

    if (await assert(conventionTool.check(feedback, feedbackConvention)))
        return;

    let result = await dbentityTool.save('feedback', feedback);
    if (await assert(result instanceof Error))
        return;

    let article = await dbentityTool.findOne('article', {_id:ObjectID(feedback.article_id)});
    if (await assert(article instanceof Error))
        return;

    let audit = {
        produceUser: feedback.produceUser,
        produceTime: datetimeTool.to_yMdHms(feedback.produceTime, '-', ' ', ':'),
        produceArticle: articleTool.getProfile(article),
        type: feedback.type,
        path: feedback.path,
        brief: feedback.relate_content + '<p>———— ' + feedback.type + ' ————</p>' + feedback.description
    };

    //提交给审核页面
    require('../appWS').io.to('publishaudit').emit('newitem', audit);

    await assert('"举报/反馈/建议"提交成功');
});
module.exports = router;